package com.jason.concurrent.readWriter;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author  yslai
 * @Date  2022/9/20 9:04
 * @Description 演示读写锁
 */

class Catch{
    private ReadWriteLock lock = new  ReentrantReadWriteLock();

    private Map<String,Object> objectMap = new HashMap<>();

    //写操作
    public void put(String key, Object object){

        //开启一个写锁
        lock.writeLock().lock();


        try {
            System.out.println(Thread.currentThread().getName()+"::开启写操作");

            TimeUnit.MILLISECONDS.sleep(300);
            objectMap.put(key,object);
            System.out.println(Thread.currentThread().getName()+"写完了");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }

    }

    //读操作
    public void get(String key){

        //开启一个写锁
        lock.readLock().lock();


        try {
            System.out.println(Thread.currentThread().getName()+"::开启读操作");

            TimeUnit.MILLISECONDS.sleep(300);
            objectMap.get(key);
            System.out.println(Thread.currentThread().getName()+"读完了");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }

    }

}
public class ReadWriteDemo {




    public static void main(String[] args) {

        Catch aCatch = new Catch();
        for (int i = 1; i <= 5; i++) {
            final int number = i;
            new Thread(()->{
                aCatch.put(number+"",number+"");
            },String.valueOf(i)).start();



        }

        for (int i = 1; i <= 5; i++) {
            final int number = i;
            new Thread(()->{
                aCatch.get(number+"");
            },String.valueOf(i)).start();

        }
    }
}
